package com.heima.wemedia.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import com.heima.model.media.dtos.WmUserLoginDto;
import com.heima.wemedia.entity.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class LoginService {
    @Autowired
    private WmUserService wmUserService;
    @Autowired
    private BCryptPasswordEncoder encoder;
    public Map<String, Object> login(WmUserLoginDto dto) {
        //根据新用户mane  查询用户  where name=?
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName, dto.getName());
        WmUser wmUser = wmUserService.getOne(queryWrapper);
        //如果用户并不存在 抛出异常
        if (wmUser == null) {
            log.error("用户不存在");
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        //匹配密码
        boolean matches = encoder.matches(dto.getPassword(), wmUser.getPassword());
        if (!matches) {
            log.error("密码错误");
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(wmUser.getId(), 120);

        wmUser.setPassword(null);
        Map<String, Object> result = new HashMap<>();

        result.put("user", wmUser);
        result.put("token", token);
        return result;
    }
}
